package com.tornainbow;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author mcrysler
 */
public class Producer {
    // Define a logger for this class
    private static final Logger logger = LoggerFactory.getLogger(Producer.class);
    
    /**
     * Sends a message which in this case is a Record object
     * @param record This becomes the contents of the message produced
     */
    public static void sendMessage(String url, String queueName, Record record) {
        // URL of the JMS server
        if (url == null || url.trim().isEmpty()) {
            url = ActiveMQConnection.DEFAULT_BROKER_URL;
        }
        logger.debug("URL has been set to {}", url);
        
        // Name of the queue we will be receiving messages from
        if (queueName == null || queueName.trim().isEmpty()) {
            queueName = "TESTQUEUE";
        }
        logger.debug("Queue name has been set to {}", queueName);
        
        try {
            // Getting JMS connection from the server
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
            Connection connection = connectionFactory.createConnection();
            connection.start();
            logger.debug("Successfully made connection to {}", url);

            // Creating session for sending messages
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            logger.debug("Successfully created session from the connection");

            // Getting the queue
            Destination destination = session.createQueue(queueName);
            logger.debug("Successfully created queue {}", queueName);

            // MessageProducer is used for sending messages
            MessageProducer producer = session.createProducer(destination);
            logger.debug("Successfully created producer");
            
            // Create the ObjectMessage from the Record object
            ObjectMessage message = session.createObjectMessage(record);
            logger.debug("Created ObjectMessage from Record object");

            // Send the ObjectMessage to the queue
            producer.send(message);
            logger.debug("Sent message to the queue");
            
            // Close the Producer
            producer.close();
            logger.debug("Successfully closed connection");
            
        } catch (JMSException e) {
            logger.error("Failed to send the message to the queue", e);
        }
    }
}